#include <nds.h>
 
#include <nds/arm9/console.h> //basic print funcionality
#include <stdio.h>
static uint16 identicPoints;
static uint16 countPoints;
static uint16 countDifPoints;
static bool didTouch;
static int oldx;
static int oldy;


void paintDownScreenBlack(){
	int i;
	for(i = 0; i < 256 * 192; i++){
		VRAM_A[i] = RGB15(0,0,0);
	}
}

void paintUpScreenBlack(){
	consoleClear();
}

void resetMeasure(){
	countPoints=0;
	countDifPoints=0;
	identicPoints=1;
	didTouch=false;
	oldx=-1;
	oldy=-1;
}

int main(){
	bool colorChange=true;
	bool basicInfo=true;
	bool globalInfo=true;
	bool countOnTime=true;
	int colorChanger=0;
	touchPosition touch;
	uint16 color = RGB15(31,31,31);
	consoleDemoInit();
	irqInit();
	irqEnable(IRQ_VBLANK);
	videoSetMode(MODE_FB0);
	vramSetBankA(VRAM_A_LCD);
	//notice we make sure the main graphics engine renders
	//to the lower lcd screen as it would be hard to draw if the 
	//pixels did not show up directly benieth the pen
	lcdMainOnBottom();
	paintDownScreenBlack();
	resetMeasure();
	printf("Greetings my panda friend !\n");
	while(1){
		scanKeys();
		if(keysDown() & KEY_SELECT){
			paintDownScreenBlack();
		}
		if(keysDown() & KEY_START){
			paintUpScreenBlack();
		}
		if(keysDown() & KEY_A){
			basicInfo = !basicInfo;
		}
		if(keysDown() & KEY_B){
			globalInfo = !globalInfo;
		}
		if(keysDown() & KEY_X){
			countOnTime = !countOnTime;
		}
		if(keysDown() & KEY_Y){
			colorChange = !colorChange;
		}
		if(keysHeld() & KEY_TOUCH){
			didTouch=true;
			countPoints++;
			//read the touchscreen coordinates
			touch=touchReadXY();
			if(touch.px == oldx && touch.py == oldy){
				identicPoints++;
			}else{
				countDifPoints++;
				if(basicInfo){
					if(oldx!=-1 && oldy !=-1){
						printf("%u fois \n", identicPoints);
					}
				}
				identicPoints=1;
				oldx = touch.px;
				oldy = touch.py;
				if(basicInfo){
					printf("x = %d y= %d  ", touch.px, touch.py);
				}
				if(colorChange){
					switch(colorChanger){
						case 0:
							color = RGB15(31,31,31);
							break;
						case 1:
							color = RGB15(0,31,31);
							break;
						case 2:
							color = RGB15(31,0,31);
							break;
						case 3:
							color = RGB15(31,31,0);;
							break;
					}
					colorChanger=(colorChanger+1)%4;
				}else{
					color = RGB15(31,31,31);
				}
				VRAM_A[touch.px + touch.py * 256] = color;	
			}
		}else{
			if(didTouch){
				if(basicInfo){
					printf("%u fois\n", identicPoints);
				}
				if(globalInfo){
 					printf("%u points, %u different(s)\n", countPoints, countDifPoints);
				}
				if(countOnTime){
				}
				resetMeasure();
			}
		}
		swiWaitForVBlank();
	}
	return 0;
}
